{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Example: Symmetry-reduced Pulse Design Tool (Anamak)\n", "\n", "---\n", "\n", "This notebook demonstrates how to use `SymmetryReducedSolver` with the **FreeGSNKE Pulse Design Tool** (FPDT) on an Anamak-like tokamak, evolving the coupled plasma/metal system strictly in the even-in-$Z$ subspace.\n", "\n", "This should enable large timesteps to be taken and rapid prototyping of plasma scenarios.\n", "\n", "In this notebook, we:\n", "1. Prepare an exactly up-down symmetric machine description.\n", "2. Construct a symmetric initial Grad-Shafranov equilibrium.\n", "3. Inspect the even and odd passive structure modes.\n", "4. Run a closed-loop FPDT simulation using `SymmetryReducedSolver` in place of `nl_solver`.\n", "\n", "Note that this is a very basic example on a tokamak with few coils, so the control demonstrated here is limited." ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "### 1. Build the analytic source machine\n", "\n", "We place active coils and passive structures in reflected pairs about $Z = 0$: five shaping pairs, one symmetric central solenoid, and one odd anti-series vertical-control circuit (included to demonstrate explicit exclusion during preparation). The fifth shaping pair sits close to the X-points: the other four pairs act almost identically on the X-point radius $R_x$ and the midplane radii, so moving $R_x$ on its own would need very large, nearly cancelling currents. The limiter radius is chosen to avoid landing directly on grid nodes." ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import time\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "from freegsnke import GSstaticsolver, build_machine, equilibrium_update\n", "from freegsnke.inverse import Inverse_optimizer\n", "from freegsnke.jtor_update import Lao85\n", "from freegsnke.up_down_symmetry import prepare_up_down_symmetric_machine" ] }, { "cell_type": "code", "execution_count": null, "id": "3", "metadata": {}, "outputs": [], "source": [ "# build the symmetric machine data\n", "def active_element(r, z, multiplier=100, polarity=1):\n", " \"\"\"Return one rectangular active-coil filament bundle.\"\"\"\n", " return {\n", " \"R\": [r],\n", " \"Z\": [z],\n", " \"dR\": 0.06,\n", " \"dZ\": 0.06,\n", " \"resistivity\": 1.55e-8,\n", " \"polarity\": polarity,\n", " \"multiplier\": multiplier,\n", " }\n", "\n", "\n", "def analytic_source_machine():\n", " \"\"\"Build an approximately machine-shaped, exactly paired toy description.\"\"\"\n", " major_radius = 1.0\n", " active = {\n", " \"solenoid\": {\n", " **active_element(0.28, 0.0, multiplier=20),\n", " \"R\": [0.28] * 4,\n", " \"Z\": [-0.55, -0.18, 0.18, 0.55],\n", " }\n", " }\n", "\n", " upper_angles = (np.pi / 4, 3 * np.pi / 4, np.pi / 8, 7 * np.pi / 8)\n", " for index, angle in enumerate(upper_angles, start=1):\n", " r = major_radius + 0.70 * np.cos(angle)\n", " z = 0.70 * np.sin(angle)\n", " active[f\"PF_{index}_upper\"] = active_element(r, z)\n", " active[f\"PF_{index}_lower\"] = active_element(r, -z)\n", "\n", " # fifth shaping pair, close to the X-points, for independent control of the X-point position\n", " active[\"PF_5_upper\"] = active_element(0.75, 0.60)\n", " active[\"PF_5_lower\"] = active_element(0.75, -0.60)\n", "\n", " active[\"vertical_control\"] = {\n", " \"upper\": active_element(1.68, 0.28),\n", " \"lower\": active_element(1.68, -0.28, polarity=-1),\n", " }\n", "\n", " passive = []\n", " for index, angle in enumerate(np.linspace(np.pi / 20, 19 * np.pi / 20, 10)):\n", " r = major_radius + 0.50 * np.cos(angle)\n", " z = 0.50 * np.sin(angle)\n", " half_width = 0.025\n", " for side, z_centre in ((\"upper\", z), (\"lower\", -z)):\n", " passive.append(\n", " {\n", " \"name\": f\"shell_{index}_{side}\",\n", " \"element\": f\"shell_{index}\",\n", " \"R\": np.array(\n", " [\n", " r - half_width,\n", " r + half_width,\n", " r + half_width,\n", " r - half_width,\n", " ]\n", " ),\n", " \"Z\": np.array(\n", " [\n", " z_centre - half_width,\n", " z_centre - half_width,\n", " z_centre + half_width,\n", " z_centre + half_width,\n", " ]\n", " ),\n", " \"resistivity\": 5.5e-7,\n", " }\n", " )\n", "\n", " theta = np.linspace(0.0, 2 * np.pi, 96, endpoint=True)\n", " limiter = [\n", " {\n", " \"R\": float(major_radius + 0.44 * np.cos(angle)),\n", " \"Z\": float(0.44 * np.sin(angle)),\n", " }\n", " for angle in theta\n", " ]\n", " return active, passive, limiter" ] }, { "cell_type": "markdown", "id": "4", "metadata": {}, "source": [ "### Build the symmetrised machine\n", "\n", "Let's build the symmetric machine (excluding the vertical control coil)." ] }, { "cell_type": "code", "execution_count": null, "id": "5", "metadata": {}, "outputs": [], "source": [ "# machine data\n", "active_source, passive_source, limiter_source = analytic_source_machine()\n", "\n", "# symmetric machine data\n", "symmetric_machine = prepare_up_down_symmetric_machine(\n", " active_source,\n", " passive_source,\n", " limiter_data=limiter_source,\n", " wall_data=limiter_source,\n", " exclude_odd_active=True,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "6", "metadata": {}, "outputs": [], "source": [ "# build machine\n", "tokamak = build_machine.tokamak(\n", " active_coils_data=symmetric_machine.even_active_coils_data,\n", " passive_coils_data=symmetric_machine.passive_coils_data,\n", " limiter_data=symmetric_machine.limiter_data,\n", " wall_data=symmetric_machine.wall_data,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "# plot machine\n", "fig, ax = plt.subplots(figsize=(6, 6), dpi=80)\n", "tokamak.plot(axis=ax, show=False)\n", "ax.plot(tokamak.limiter.R, tokamak.limiter.Z, \"k-\", linewidth=1.2)\n", "ax.set( xlabel=\"Major radius, R [m]\", ylabel=\"Height, Z [m]\", aspect=\"equal\")\n", "ax.grid(zorder=0, alpha=0.75)\n", "ax.set_aspect('equal')\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "### 2. Construct a symmetric initial equilibrium\n", "\n", "Let's use the inverse solver to build an initial equilibrium. " ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "# initialise eq\n", "eq = equilibrium_update.Equilibrium(\n", " tokamak=tokamak,\n", " Rmin=0.1,\n", " Rmax=1.9,\n", " Zmin=-0.8,\n", " Zmax=0.8,\n", " nx=65,\n", " ny=65,\n", ")\n", "\n", "# initialise profiles\n", "profiles = Lao85(\n", " eq=eq,\n", " Ip=2.0e5,\n", " fvac=0.5,\n", " alpha=[58213.6],\n", " beta=[0.582136],\n", ")\n", "\n", "# static solver\n", "static_solver = GSstaticsolver.NKGSsolver(eq)" ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "# constraints for inverse solver\n", "tokamak.set_coil_current(\"solenoid\", 3000.0)\n", "tokamak[\"solenoid\"].control = False\n", "\n", "# the extra shaping pair carries no current in the initial equilibrium (so the equilibrium is\n", "# unchanged); it is only used by the shape controllers\n", "tokamak.set_coil_current(\"PF_5\", 0.0)\n", "tokamak[\"PF_5\"].control = False\n", "\n", "constrain = Inverse_optimizer(\n", " null_points=[[0.8, 0.8], [0.35, -0.35]],\n", " isoflux_set=np.array([[[0.8, 0.8, 1.22], [0.35, -0.35, 0.0]]]),\n", " weight_isoflux=1.0,\n", " weight_nulls=0.8,\n", ")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "11", "metadata": {}, "outputs": [], "source": [ "# the numerical operators need exactly up-down symmetric resistances and inductances, so these calls enforce this\n", "eq._vgreen = symmetric_machine.symmetrise_even_machine_greens(eq._vgreen)\n", "tokamak.coil_resist = symmetric_machine.symmetrise_even_machine_resistances(\n", " tokamak.coil_resist\n", ")\n", "tokamak.coil_self_ind = symmetric_machine.symmetrise_even_machine_square_operator(\n", " tokamak.coil_self_ind\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "# solve and plot\n", "static_solver.inverse_solve(\n", " eq=eq,\n", " profiles=profiles,\n", " constrain=constrain,\n", " target_relative_tolerance=1e-5,\n", " target_relative_psit_update=1e-3,\n", " l2_reg=np.full(4, 1e-8),\n", " force_up_down_symmetric=True,\n", " verbose=False,\n", ")\n" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "We should have a nice up-down symmetric equilibrium in the symmetric machine!" ] }, { "cell_type": "code", "execution_count": null, "id": "14", "metadata": {}, "outputs": [], "source": [ "# plot the equilibrium\n", "fig1, ax1 = plt.subplots(1, 1, figsize=(7, 15), dpi=80)\n", "ax1.grid(zorder=0, alpha=0.75)\n", "ax1.set_aspect('equal')\n", "eq.tokamak.plot(axis=ax1,show=False) # plots the active coils and passive structures\n", "ax1.fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0) # plots the limiter\n", "eq.plot(axis=ax1,show=False) # plots the equilibrium\n", "constrain.plot(axis=ax1, show=False) # plots the constraints" ] }, { "cell_type": "markdown", "id": "15", "metadata": {}, "source": [ "If needed we can do some checks to ensure everything is fully up-down symmetric (i.e. machine operators commute with the metal-current reflection, the limiter mask is reflection-invariant, and the initial plasma fields and metal currents are even to round-off). " ] }, { "cell_type": "code", "execution_count": null, "id": "16", "metadata": {}, "outputs": [], "source": [ "passive_reflection_operator = symmetric_machine.passive_reflection_operator\n", "reflection_operator = symmetric_machine.even_machine_reflection_operator\n", "\n", "\n", "def relative_reflection_error(values, parity=1):\n", " denominator = np.linalg.norm(values)\n", " if denominator == 0:\n", " return 0.0\n", " return np.linalg.norm(values - parity * values[:, ::-1]) / denominator\n", "\n", "\n", "def relative_commutator_error(matrix):\n", " numerator = np.linalg.norm(\n", " reflection_operator @ matrix - matrix @ reflection_operator\n", " )\n", " return numerator / np.linalg.norm(matrix)\n", "\n", "\n", "reflected_greens = np.einsum(\n", " \"ij,jrz->irz\", reflection_operator, eq._vgreen[:, :, ::-1]\n", ")\n", "resistance_matrix = np.diag(tokamak.coil_resist)\n", "initial_currents = tokamak.getCurrentsVec()\n", "symmetry_errors = {\n", " \"sampled Green functions\": (\n", " np.linalg.norm(eq._vgreen - reflected_greens)\n", " / np.linalg.norm(eq._vgreen)\n", " ),\n", " \"inductance operator\": relative_commutator_error(tokamak.coil_self_ind),\n", " \"resistance operator\": relative_commutator_error(resistance_matrix),\n", " \"plasma flux\": relative_reflection_error(eq.plasma_psi),\n", " \"toroidal current density\": relative_reflection_error(profiles.jtor),\n", " \"metal currents\": (\n", " np.linalg.norm(reflection_operator @ initial_currents - initial_currents)\n", " / np.linalg.norm(initial_currents)\n", " ),\n", "}\n", "limiter_defects = np.count_nonzero(\n", " eq.limiter_handler.mask_inside_limiter\n", " != eq.limiter_handler.mask_inside_limiter[:, ::-1]\n", ")\n", "\n", "for name, error in symmetry_errors.items():\n", " print(f\"{name:27s}: {error:.3e}\")\n", "print(f\"{'limiter-mask defects':27s}: {limiter_defects}\")\n", "assert max(symmetry_errors.values()) < 1e-12\n", "assert limiter_defects == 0" ] }, { "cell_type": "markdown", "id": "17", "metadata": {}, "source": [ "### 3. Build the virtual circuits for the PCS\n", "\n", "We use FreeGSNKE's `VirtualCircuitHandling` class (see Example 09) to build the virtual circuits for the five shaping circuits. It computes, by finite differences of static GS solves, the shape sensitivity matrix\n", "\n", "$$\n", "S_{kj} = \\frac{\\partial s_k}{\\partial I_j},\n", "$$\n", "\n", "where $s_k$ are the shape targets (`Rin`, `Rout`, `Rx`, `Zx`) and $I_j$ the shaping-circuit currents, and its pseudo-inverse $S^+$ (the virtual circuits), which maps requested shape corrections to coil-current commands. The solenoid is excluded because it is reserved for plasma-current control.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": {}, "outputs": [], "source": [ "# functions for the plasma descriptors (shape functions)\n", "def selected_lower_xpoint(equilibrium):\n", " \"\"\"Select the lower null nearest the inverse-solve target.\"\"\"\n", " lower = equilibrium.xpt[equilibrium.xpt[:, 1] < 0]\n", " target = np.array([0.8, -0.35])\n", " return lower[np.argmin(np.linalg.norm(lower[:, :2] - target, axis=1)), :2]\n", "\n", "\n", "def plasma_descriptors(equilibrium):\n", " \"\"\"Return the four shape measurements used by the controller.\"\"\"\n", " rin, rout = equilibrium.innerOuterSeparatrix()\n", " rx, zx = selected_lower_xpoint(equilibrium)\n", " return np.array([rin, rout, rx, zx])\n", "\n", "# calculate initial values\n", "baseline_descriptors = plasma_descriptors(eq)\n", "\n", "active_coils = list(tokamak.coils_list[: tokamak.n_active_coils])\n", "shape_coils = [name for name in active_coils if name != \"solenoid\"]\n", "ctrl_targets = [\"Rin\", \"Rout\", \"Rx\", \"Zx\"]\n", "\n", "print(\"Active circuit order:\", active_coils)\n", "print(\"Shape parameters:\", ctrl_targets)\n", "print(\"Initial descriptors [m]:\", baseline_descriptors)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "19", "metadata": {}, "outputs": [], "source": [ "from freegsnke import virtual_circuits\n", "\n", "# build the VCs\n", "VCs = virtual_circuits.VirtualCircuitHandling()\n", "VCs.define_solver(static_solver)\n", "VCs.calculate_VC(\n", " eq=eq,\n", " profiles=profiles,\n", " coils=shape_coils,\n", " target_names=ctrl_targets,\n", " target_calculator=plasma_descriptors,\n", " n_vc_workers=2,\n", " verbose=True,\n", " name=\"VC_shape\",\n", ")\n", "\n", "shape_matrix = VCs.VC_shape.shape_matrix # [no. of targets x no. of coils], units m/A\n", "shape_vcs = VCs.VC_shape.VCs_matrix # [no. of coils x no. of targets], units A/m" ] }, { "cell_type": "markdown", "id": "20", "metadata": {}, "source": [ "### 4. Configure the plasma-control loop\n", "\n", "Here we set up the FPDT controllers as in Example 11, holding the plasma current and all but one of the shape targets at their initial values, so that the controllers must counteract the resistive decay of the plasma current and any drift in the plasma shape. The X-point radius, $R_x$, is ramped outwards by 5 cm between 25% and 75% of the simulation. The shape controllers use proportional-integral (PI) control, so they remove steady offsets." ] }, { "cell_type": "code", "execution_count": null, "id": "21", "metadata": {}, "outputs": [], "source": [ "from freegsnke.control_loop.pcs import PlasmaControlSystem\n", "\n", "tmin = 0.0\n", "tmax = 1.0\n", "waveform_times = np.array([tmin, tmax])\n", "zeros = {\"times\": waveform_times, \"vals\": np.zeros(2)}\n", "\n", "plasma_data = {\n", " \"ip_ref\": {\"times\": waveform_times, \"vals\": np.full(2, profiles.Ip)},\n", " \"vloop_ff\": zeros,\n", " \"ip_blend\": {\"times\": waveform_times, \"vals\": np.ones(2)},\n", " \"k_prop\": {\"times\": np.array([tmin]), \"vals\": np.array([-20.0])},\n", " \"k_int\": {\"times\": np.array([tmin]), \"vals\": np.array([-100.0])},\n", " \"k_deriv\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", " \"M_solenoid\": {\"times\": np.array([tmin]), \"vals\": np.array([1.0])},\n", "}\n", "\n", "initial_shape = dict(zip(ctrl_targets, baseline_descriptors))\n", "shape_data = {}\n", "for target in ctrl_targets:\n", " shape_data[target] = {\n", " \"ff\": zeros,\n", " \"ref\": {\n", " \"times\": waveform_times,\n", " \"vals\": np.full(2, initial_shape[target]),\n", " },\n", " \"blend\": {\"times\": waveform_times, \"vals\": np.ones(2)},\n", " \"k_prop\": {\"times\": np.array([tmin]), \"vals\": np.array([25.0])},\n", " \"k_int\": {\"times\": np.array([tmin]), \"vals\": np.array([100.0])},\n", " \"k_deriv\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", " }" ] }, { "cell_type": "markdown", "id": "22", "metadata": {}, "source": [ "### Virtual circuits and electrical limits\n", "\n", "The shape virtual circuits are the columns of $S^+$ (padded with zero on the solenoid), while the plasma-current virtual circuit acts solely on the solenoid. Electrical limits, resistances, and inductances are taken directly from the analytic tokamak object." ] }, { "cell_type": "code", "execution_count": null, "id": "23", "metadata": {}, "outputs": [], "source": [ "n_active = tokamak.n_active_coils\n", "\n", "circuits_data = {\"coil_order\": active_coils}\n", "for target_index, target in enumerate(ctrl_targets):\n", " circuit = np.zeros(n_active)\n", " circuit[1:] = shape_vcs[:, target_index]\n", " circuits_data[target] = {\"times\": np.array([tmin]), \"vals\": [circuit]}\n", "circuits_data[\"plasma\"] = {\n", " \"times\": np.array([tmin]),\n", " \"vals\": [np.r_[1.0, np.zeros(n_active - 1)]],\n", "}\n", "for coil_name in active_coils:\n", " circuits_data[f\"{coil_name}_ref\"] = zeros\n", "\n", "initial_active = tokamak.getCurrentsVec()[:n_active]\n", "current_margin = np.maximum(5000.0, 2.0 * np.abs(initial_active))\n", "min_current_lims = initial_active - current_margin\n", "max_current_lims = initial_active + current_margin\n", "# the solenoid current is limited to +/-10 kA\n", "solenoid_index = active_coils.index(\"solenoid\")\n", "min_current_lims[solenoid_index] = -10e3\n", "max_current_lims[solenoid_index] = 10e3\n", "systems_data = {\n", " \"min_coil_curr_lims\": {\n", " \"times\": [tmin],\n", " \"vals\": [min_current_lims],\n", " },\n", " \"max_coil_curr_lims\": {\n", " \"times\": [tmin],\n", " \"vals\": [max_current_lims],\n", " },\n", " \"max_coil_curr_ramp_lims\": {\n", " \"times\": [tmin],\n", " \"vals\": [1e12 * np.ones(n_active)],\n", " },\n", "}\n", "for coil_name in active_coils:\n", " systems_data[f\"{coil_name}_pert\"] = zeros\n", "\n", "pf_data = {\n", " \"R_matrix\": {\"times\": [tmin], \"vals\": [tokamak.coil_resist[:n_active]]},\n", " \"M_FF_matrix\": {\n", " \"times\": [tmin],\n", " \"vals\": [tokamak.coil_self_ind[:n_active, :n_active]],\n", " },\n", " \"M_FB_matrix\": {\n", " \"times\": [tmin],\n", " \"vals\": [tokamak.coil_self_ind[:n_active, :n_active]],\n", " },\n", " \"coil_gains\": {\n", " \"times\": [tmin],\n", " \"vals\": [0.015 * np.ones(n_active)],\n", " },\n", " \"coil_voltage_lims\": {\n", " \"times\": np.array([tmin]),\n", " \"vals\": [[2000.0] + [750.0] * (n_active - 1)],\n", " },\n", " \"coil_voltage_slew_lims\": {\n", " \"times\": [tmin],\n", " \"vals\": [1e12 * np.ones(n_active)],\n", " },\n", "}\n", "vertical_data = {\n", " \"z_ref\": {\"times\": waveform_times, \"vals\": np.zeros(2)},\n", " \"k_prop\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", " \"k_deriv\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", "}\n", "activation_data = {\n", " f\"{name}_activation\": {\n", " \"times\": np.array([tmin]),\n", " \"vals\": np.array([1.0]),\n", " }\n", " for name in active_coils\n", "}" ] }, { "cell_type": "markdown", "id": "24", "metadata": {}, "source": [ "### Assemble the PCS\n", "\n", "The standard `PCS` interface is unchanged: symmetry reduction is handled entirely by the evolutive solver." ] }, { "cell_type": "code", "execution_count": null, "id": "25", "metadata": {}, "outputs": [], "source": [ "# build\n", "pcs = PlasmaControlSystem(\n", " plasma_data=plasma_data,\n", " shape_data=shape_data,\n", " shape_control_mode=\"PID\",\n", " circuits_data=circuits_data,\n", " systems_data=systems_data,\n", " pf_data=pf_data,\n", " vertical_data=vertical_data,\n", " coil_activation_data=activation_data,\n", " active_coils=active_coils,\n", " ctrl_coils=active_coils,\n", " vertical_coils=[],\n", " ctrl_targets=ctrl_targets,\n", " plasma_target=[\"plasma\"],\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "26", "metadata": {}, "outputs": [], "source": [ "# ramp Rx outwards by 5 cm between 25% and 75% of the simulation (the other shape targets are held)\n", "rx_initial = initial_shape[\"Rx\"]\n", "pcs.ShapeController.data[\"Rx\"][\"ref\"] = {\n", " \"times\": np.array([tmin, 0.25 * tmax, 0.75 * tmax, tmax]),\n", " \"vals\": np.array([rx_initial, rx_initial, rx_initial + 0.05, rx_initial + 0.05]),\n", "}\n", "pcs.ShapeController.update_interpolants()\n" ] }, { "cell_type": "markdown", "id": "27", "metadata": {}, "source": [ "### 5. Initialise the reduced evolutive solver\n", "\n", "In Example 10 we showed that the metals and the plasma are governed by the circuit equation (2) and the plasma equation (3). Linearising the plasma current density about the current equilibrium (equation (4)) gives the state-matrix system\n", "\n", "$$\n", "\\mathbf{M}\\dot{\\mathbf{x}} + \\mathbf{R}\\mathbf{x} = \\mathbf{c}, \\qquad \\mathbf{x} = \\begin{bmatrix} \\vec{I}_m \\\\ I_p \\end{bmatrix}, \\qquad A = -\\mathbf{R}^{-1}\\mathbf{M},\n", "$$\n", "\n", "where the eigenvalues of $A$ are the timescales $\\tau_i$ of the system ($\\tau_i > 0$ unstable, $\\tau_i < 0$ stable). The `nl_solver` used in Examples 05 and 11 evolves all of these modes (or a subset if needed). This includes the fast, vertically unstable mode, whose short timescale forces a small timestep (0.5 ms in Example 11).\n", "\n", "`SymmetryReducedSolver` removes that mode by exploiting the up-down symmetry of the machine and the equilibrium. Let $S_m$ be the reflection operator for the metal currents (it swaps each upper/lower partner) and $S_y$ the reflection of the plasma grid about $Z = 0$. For an exactly symmetric machine and equilibrium, reflected partners have equal resistances and inductances, and the Jacobians in equation (4) are even fields. The linearised system then commutes with reflection, $SA = AS$ with $S = \\mathrm{diag}(S_m, 1)$, so the even and odd parts of the state evolve independently: an even perturbation never drives an odd response. The vertical instability is a vertical displacement of the plasma, which is odd, so it lives in the odd part and is removed by keeping only the even part.\n", "\n", "#### How the passive modes are calculated\n", "\n", "The passive structures obey the circuit equation (2) with no plasma and no applied voltage:\n", "\n", "$$\n", "M_{p,p}\\dot{\\vec{I}}_p + R_{p,p}\\vec{I}_p = 0.\n", "$$\n", "\n", "We form $A_p = -R_{p,p}^{-1}M_{p,p}$ and solve the eigenproblem\n", "\n", "$$\n", "A_p\\vec{v}_i = \\tau_i\\vec{v}_i.\n", "$$\n", "\n", "Each eigenvector $\\vec{v}_i$ is a pattern of passive currents that decays as $e^{t/\\tau_i}$. All $\\tau_i$ are negative because the passive structures only dissipate energy. The modes are stored with their decay rates $1/|\\tau_i|$ and sorted from lowest rate (slowest decay) upwards.\n", "\n", "For $n=20$ passive elements, we obtain $n/2 = 10$ up-down symmetric pairs. The passive reflection operator $S_p$ is a permutation matrix, built from the pairing found by `prepare_up_down_symmetric_machine`, that swaps each upper/lower partner. For a pair $(u, l)$:\n", "\n", "- the $S_p = +1$ eigenvector is $(e_u + e_l)/\\sqrt{2}$: both partners carry the same current, giving flux that is **even** in $Z$.\n", "- the $S_p = -1$ eigenvector is $(e_u - e_l)/\\sqrt{2}$: the partners carry opposite currents, giving a field that is **odd** in $Z$. This is the kind of current that responds to vertical plasma motion.\n", "\n", "The 10 pairs therefore give a 10-dimensional even subspace and a 10-dimensional odd subspace. A passive element on the midplane has no partner and contributes to the even subspace only.\n", "\n", "We solve the eigenproblem separately in each subspace, so every mode has a definite parity, even when eigenvalues are degenerate. This requires $S_pA_p = A_pS_p$, which holds when the resistances and inductances are reflection-symmetric. The solver checks this and raises an error if it fails.\n", "\n", "#### What the reduced solver evolves\n", "\n", "We keep only (a subset of) the even modes. The metal currents are written as $\\vec{I}_m = P\\vec{\\alpha}$, where the columns of $P$ are the active-coil unit vectors and the retained even passive modes (in the following cell, we will retain 6 of the 10 even modes). The odd modes are removed before the plasma coupling is built. The reduced state is then\n", "\n", "$$\n", "\\mathbf{x}_+ = \\begin{bmatrix} \\vec{\\alpha} \\\\ I_p \\end{bmatrix} \\qquad (6 \\text{ active circuits} + 6 \\text{ passive modes} + I_p = 13 \\text{ values}).\n", "$$\n", "\n", "Substituting $\\vec{I}_m = P\\vec{\\alpha}$ into equation (5), multiplying by $P^{-1}R_{m,m}^{-1}$, and dividing equation (6) by the lumped plasma resistance $R_p$ gives the same equations as Example 10 in the reduced state:\n", "\n", "$$\n", "\\mathbf{M}_+\\dot{\\mathbf{x}}_+ + \\mathbf{x}_+ = \\mathbf{f},\n", "$$\n", "\n", "$$\n", "\\mathbf{M}_+ =\n", "\\begin{bmatrix}\n", "P^{-1}R_{m,m}^{-1}\\left( M_{m,m}P + M_{m,y}\\dfrac{\\partial \\vec{I}_y}{\\partial \\vec{\\alpha}} \\right) &\n", "P^{-1}R_{m,m}^{-1}M_{m,y}\\dfrac{\\partial \\vec{I}_y}{\\partial I_p} \\\\[2ex]\n", "\\dfrac{\\hat{\\vec{I}}_y^{T}}{R_p}\\left( M_{y,m}P + M_{y,y}\\dfrac{\\partial \\vec{I}_y}{\\partial \\vec{\\alpha}} \\right) &\n", "\\dfrac{\\hat{\\vec{I}}_y^{T}}{R_p}M_{y,y}\\dfrac{\\partial \\vec{I}_y}{\\partial I_p}\n", "\\end{bmatrix},\n", "$$\n", "\n", "$$\n", "\\mathbf{f} =\n", "\\begin{bmatrix} P^{-1}R_{m,m}^{-1}\\vec{V}_m \\\\ 0 \\end{bmatrix}\n", "-\n", "\\begin{bmatrix} P^{-1}R_{m,m}^{-1}M_{m,y} \\\\[1ex] \\dfrac{\\hat{\\vec{I}}_y^{T}}{R_p}M_{y,y} \\end{bmatrix}\n", "\\dfrac{\\partial \\vec{I}_y}{\\partial \\vec{\\theta}}\\dot{\\vec{\\theta}}.\n", "$$\n", "\n", "The Jacobians $\\partial\\vec{I}_y/\\partial\\vec{\\alpha}$, $\\partial\\vec{I}_y/\\partial I_p$ and $\\partial\\vec{I}_y/\\partial\\vec{\\theta}$ come from Grad-Shafranov solves forced to be even in $Z$, and are projected with $\\Pi_+ = \\tfrac{1}{2}(I + S_y)$ to remove odd round-off. The system is advanced with implicit Euler,\n", "\n", "$$\n", "\\mathbf{x}_+(t + \\Delta t) = (\\mathbf{M}_+ + \\Delta t\\,\\mathbf{I})^{-1}\\left(\\Delta t\\,\\mathbf{f} + \\mathbf{M}_+\\mathbf{x}_+(t)\\right).\n", "$$\n", "\n", "After each step the equilibrium is updated with a Grad-Shafranov solve, and the Jacobians are rebuilt if the plasma current density has changed by more than the relinearisation threshold.\n", "\n", "**Note:** Without the odd modes, the fastest remaining timescales are resistive, which allows a much larger timestep to be taken (recall the small timesteps used in Examples 05 and 11). This is exact only for the linearisation about an even equilibrium in an even machine: the plasma cannot move vertically, so it cannot be used for vertical displacement events or asymmetric scenarios. The timestep cannot be arbitrarily large, however: it must still resolve the retained dynamics, keep the linearisation accurate (the Jacobians are rebuilt whenever the plasma has changed significantly), and be small compared with the timescales and gains used in the virtual PCS." ] }, { "cell_type": "code", "execution_count": null, "id": "28", "metadata": {}, "outputs": [], "source": [ "from freegsnke.symmetry_reduced_solve import SymmetryReducedSolver\n", "\n", "# plasma resistivity [Ohm m]: sets how quickly the plasma current decays without control\n", "plasma_resistivity = 1e-8\n", "\n", "# initialise the solver object\n", "stepping = SymmetryReducedSolver(\n", " eq=eq,\n", " profiles=profiles,\n", " GSStaticSolver=static_solver,\n", " full_timestep=2.5e-3, # <-- 2.5 ms timestep!\n", " max_internal_timestep=2.5e-3,\n", " plasma_resistivity=plasma_resistivity,\n", " fix_n_vessel_modes=6, # <-- 6/10 retained modes\n", " plasma_descriptor_function=plasma_descriptors,\n", " passive_reflection_operator=passive_reflection_operator,\n", " n_linearization_workers=2,\n", " verbose=False,\n", ")\n" ] }, { "cell_type": "markdown", "id": "29", "metadata": {}, "source": [ "### Inspect passive-mode parity and truncation\n", "\n", "Open markers show the discarded passive modes (even in blue, odd in orange); filled markers show the even modes retained after parity and mode-count selection (we keep the 6 slowest-decaying even modes). The spatial panels show representative even and odd mode current patterns." ] }, { "cell_type": "code", "execution_count": null, "id": "30", "metadata": {}, "outputs": [], "source": [ "normal_modes = stepping.evol_metal_curr.normal_modes\n", "passive_parity = normal_modes.passive_mode_parity\n", "passive_frequency = normal_modes.w_passive\n", "retained_passive = stepping.evol_metal_curr.selected_modes_mask[n_active:]\n", "passive_centres = np.array(\n", " [\n", " [np.mean(element[\"R\"]), np.mean(element[\"Z\"])]\n", " for element in symmetric_machine.passive_coils_data\n", " ]\n", ")\n", "\n", "representative_modes = {\n", " \"even mode\": np.flatnonzero(passive_parity > 0)[0],\n", " \"odd mode\": np.flatnonzero(passive_parity < 0)[0],\n", "}\n", "fig, axes = plt.subplots(1, 3, figsize=(13, 4))\n", "\n", "for parity, label, colour in ((1, \"even\", \"tab:blue\"), (-1, \"odd\", \"tab:orange\")):\n", " parity_mask = (passive_parity == parity) & ~retained_passive\n", " axes[0].scatter(\n", " np.flatnonzero(parity_mask),\n", " passive_frequency[parity_mask],\n", " facecolors=\"none\",\n", " edgecolors=colour,\n", " label=f\"{label}, discarded\",\n", " )\n", "retained_indices = np.flatnonzero(retained_passive)\n", "axes[0].scatter(\n", " retained_indices,\n", " passive_frequency[retained_passive],\n", " color=\"tab:blue\",\n", " label=\"even, retained\",\n", ")\n", "axes[0].set_yscale(\"log\")\n", "axes[0].set_xlabel(\"passive-mode index\")\n", "axes[0].set_ylabel(\"frequency [s$^{-1}$]\")\n", "axes[0].set_title(\"Parity-aware mode selection\")\n", "axes[0].grid(True)\n", "axes[0].legend()\n", "\n", "for axis, (title, mode_index) in zip(axes[1:], representative_modes.items()):\n", " amplitudes = normal_modes.Pmatrix[\n", " n_active:, n_active + mode_index\n", " ]\n", " scale = np.max(np.abs(amplitudes))\n", " points = axis.scatter(\n", " passive_centres[:, 0],\n", " passive_centres[:, 1],\n", " c=amplitudes,\n", " cmap=\"coolwarm\",\n", " vmin=-scale,\n", " vmax=scale,\n", " s=70,\n", " edgecolor=\"k\",\n", " )\n", " axis.axhline(0.0, color=\"0.6\", linewidth=1)\n", " axis.set_aspect(\"equal\")\n", " axis.set_xlabel(\"R [m]\")\n", " axis.set_ylabel(\"Z [m]\")\n", " axis.set_title(title)\n", " fig.colorbar(points, ax=axis, label=\"relative mode current\")\n", "\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "31", "metadata": {}, "source": [ "### 6. Run the controlled evolution\n", "\n", "Next, we'll run the simulation with a 2.5 ms solver step and a 1.25 ms PCS timestep.\n", "\n", "The virtual PCS will return the voltages to be applied to the active coils, which the reduced solver will use to advance the retained metal modes, plasma current, and profile response (and equilibrium!).\n", "\n", "The PCS holds the plasma current at its initial value, and all shape targets at their initial values except $R_x$, which is ramped outwards by 5 cm. The plasma resistivity is set to $10^{-8}\\,\\Omega\\,\\mathrm{m}$, so the resistive loss in plasma current that the solenoid must make up stays within its $\\pm 10$ kA current limit." ] }, { "cell_type": "code", "execution_count": null, "id": "32", "metadata": {}, "outputs": [], "source": [ "# setup and storage\n", "dt = stepping.dt_step\n", "n_steps = int(round((tmax - tmin) / dt)) + 1 # simulate from tmin to tmax\n", "dt_pcs = dt / 2\n", "times = tmin + np.arange(n_steps) * dt\n", "stepping.initialize_from_ICs(eq, profiles)\n", "\n", "# keep four equilibrium snapshots, evenly spaced in time, for plotting later\n", "snapshot_indices = np.linspace(0, n_steps - 1, 4).astype(int)\n", "snapshots = {0: stepping.eq1.create_auxiliary_equilibrium()}\n", "\n", "# re-linearisation: the solver re-linearises when the relative change in the toroidal current density\n", "# since the last linearisation reaches this threshold (we store this criterion at every step)\n", "relinearise_threshold = 0.05\n", "relinearise_criterion = np.zeros(n_steps - 1)\n", "\n", "dynamic_psi = np.zeros((*eq.psi().shape, n_steps))\n", "dynamic_currents = np.zeros((len(stepping.vessel_currents_vec), n_steps))\n", "dynamic_ip = np.zeros(n_steps)\n", "dynamic_shape = np.zeros((len(ctrl_targets), n_steps))\n", "dynamic_z = np.zeros(n_steps)\n", "voltages = np.zeros((n_active, n_steps - 1))\n", "step_times = np.zeros(n_steps - 1)\n", "\n", "dynamic_psi[:, :, 0] = stepping.eq1.psi()\n", "dynamic_currents[:, 0] = stepping.vessel_currents_vec\n", "dynamic_ip[0] = stepping.profiles1.Ip\n", "dynamic_shape[:, 0] = plasma_descriptors(stepping.eq1)\n", "dynamic_z[0] = stepping.eq1.Zcurrent()\n", "\n", "ip_hist_prev = 0.0\n", "ip_err_prev = 0.0\n", "shape_error_prev = np.zeros(len(ctrl_targets))\n", "shape_history_prev = np.zeros(len(ctrl_targets))\n", "approved_current_prev = initial_active.copy()\n", "approved_voltage_prev = np.zeros(n_active)" ] }, { "cell_type": "code", "execution_count": null, "id": "33", "metadata": {}, "outputs": [], "source": [ "# simulate!\n", "for index, time_value in enumerate(times[:-1]):\n", " \n", " print(\"-----\")\n", " print(f\"t = {np.round(time_value,5)}s (step {index+1}/{n_steps-1})\")\n", " \n", " \n", " result = pcs.calculate_ctrl_voltages(\n", " t=time_value,\n", " dt=dt_pcs,\n", " dt_simulator=dt,\n", " ip_meas=dynamic_ip[index],\n", " ip_hist_prev=ip_hist_prev,\n", " ip_err_prev=ip_err_prev,\n", " T_meas=dynamic_shape[:, index],\n", " T_err_prev=shape_error_prev,\n", " T_hist_prev=shape_history_prev,\n", " I_approved_prev=approved_current_prev,\n", " I_meas=dynamic_currents[:n_active, index],\n", " V_approved_prev=approved_voltage_prev,\n", " zip_meas=dynamic_z[index] * dynamic_ip[index],\n", " zipv_meas=0.0,\n", " active_coil_resists=tokamak.coil_resist[:n_active],\n", " verbose=False,\n", " )\n", " (\n", " approved_voltage,\n", " ip_hist_prev,\n", " ip_err_prev,\n", " shape_error_prev,\n", " shape_history_prev,\n", " approved_current_prev,\n", " active_resistances,\n", " ) = result\n", " voltages[:, index] = approved_voltage\n", " approved_voltage_prev = approved_voltage.copy()\n", "\n", " start = time.perf_counter()\n", " stepping.nlstepper(\n", " plasma_resistivity=plasma_resistivity,\n", " active_voltage_vec=approved_voltage,\n", " # Lao logic adds one dependent closure coefficient to each stored\n", " # array; the evolutive interface accepts the independent values only.\n", " profiles_parameters={\n", " \"alpha\": profiles.alpha[:-1].copy(),\n", " \"beta\": profiles.beta[:-1].copy(),\n", " },\n", " custom_active_coil_resistances=active_resistances,\n", " linear_only=True,\n", " target_relative_tol_currents=1e-2,\n", " target_relative_tol_GS=1e-2,\n", " working_relative_tol_GS=5e-3,\n", " max_solving_iterations=20,\n", " relinearise_threshold=relinearise_threshold,\n", " no_GS=False,\n", " verbose=False,\n", " )\n", " step_times[index] = time.perf_counter() - start\n", " relinearise_criterion[index] = stepping.relinearise_criteria\n", "\n", " # dynamic_psi[:, :, index + 1] = stepping.eq1.psi()\n", " dynamic_currents[:, index + 1] = stepping.vessel_currents_vec\n", " dynamic_ip[index + 1] = stepping.profiles1.Ip\n", " dynamic_shape[:, index + 1] = plasma_descriptors(stepping.eq1)\n", " dynamic_z[index + 1] = stepping.eq1.Zcurrent()\n", " if index + 1 in snapshot_indices:\n", " snapshots[index + 1] = stepping.eq1.create_auxiliary_equilibrium()\n", "\n", "\n", " # print some stuff to track solve\n", " print(f\" PLASMA QUANTITIES\")\n", " print(f\" Ip = {np.round(dynamic_ip[index+1]/1000,1)} [kA]\")\n", " print(f\" Shape parameters {ctrl_targets} = {np.round(dynamic_shape[:,index+1],3)}\")\n", " print(f\" Z position = {np.round(dynamic_z[index+1],5)} [m]\")\n" ] }, { "cell_type": "markdown", "id": "34", "metadata": {}, "source": [ "### 7. Inspect the results\n", "\n", "Below we plot the plasma current and shape against their reference targets, followed by the active coil currents (with the solenoid's PCS current limits) and voltages, snapshots of the equilibrium as it evolves, and finally the passive structure currents.\n", "\n", "Note the slightly non-physical solenoid current that is compensating a bit for the lack of shaping coils. " ] }, { "cell_type": "code", "execution_count": null, "id": "35", "metadata": {}, "outputs": [], "source": [ "t_ms = 1e3 * times\n", "shape_reference = np.array( # reference waveform of each shape target, evaluated at the simulation times\n", " [\n", " np.interp(\n", " times,\n", " pcs.ShapeController.data[target][\"ref\"][\"times\"],\n", " pcs.ShapeController.data[target][\"ref\"][\"vals\"],\n", " )\n", " for target in ctrl_targets\n", " ]\n", ")\n", "t_voltage_ms = 1e3 * times[:-1] # each voltage request is applied from the start of its step\n", "colours = {name: f\"C{index}\" for index, name in enumerate(active_coils)}\n", "\n", "# plasma current and shape: evolved values against their reference targets\n", "ip_reference = np.interp(times, plasma_data[\"ip_ref\"][\"times\"], plasma_data[\"ip_ref\"][\"vals\"])\n", "fig, axes = plt.subplots(2, 3, figsize=(12, 6), dpi=80, sharex=True, constrained_layout=True)\n", "ip_axis = axes[0, 0]\n", "shape_axes = [axes[0, 1], axes[0, 2], axes[1, 0], axes[1, 1]]\n", "axes[1, 2].axis(\"off\") # unused\n", "\n", "ip_axis.plot(t_ms, dynamic_ip / 1e3, color=\"k\", label=\"evolved\")\n", "ip_axis.plot(t_ms, ip_reference / 1e3, color=\"tab:red\", linestyle=\"--\", label=\"reference\")\n", "ip_axis.set_ylabel(r\"Plasma current, $I_p$ [kA]\")\n", "ip_axis.legend()\n", "\n", "for target_index, (axis, target) in enumerate(zip(shape_axes, ctrl_targets)):\n", " axis.plot(t_ms, dynamic_shape[target_index], color=\"k\", label=\"evolved\")\n", " axis.plot(t_ms, shape_reference[target_index], color=\"tab:red\", linestyle=\"--\", label=\"reference\")\n", " axis.set_ylabel(f\"{target} [m]\")\n", "\n", "for axis in [ip_axis] + shape_axes:\n", " axis.grid(alpha=0.5)\n", "for axis in (axes[0, 2], axes[1, 0], axes[1, 1]):\n", " axis.tick_params(labelbottom=True)\n", " axis.set_xlabel(\"Time [ms]\")\n", "fig.suptitle(\"Plasma current and shape: evolved against reference\")\n", "plt.show()\n", "\n", "# active coil currents and voltages (solenoid and shape coils are shown separately)\n", "solenoid = active_coils.index(\"solenoid\")\n", "shape_coil_indices = [index for index in range(n_active) if index != solenoid]\n", "min_current_limits = systems_data[\"min_coil_curr_lims\"][\"vals\"][0]\n", "max_current_limits = systems_data[\"max_coil_curr_lims\"][\"vals\"][0]\n", "\n", "fig, axes = plt.subplots(2, 2, figsize=(12, 6), dpi=80, sharex=True, constrained_layout=True)\n", "\n", "axes[0, 0].plot(t_ms, dynamic_currents[solenoid] / 1e3, color=colours[\"solenoid\"], label=\"solenoid\")\n", "axes[0, 0].axhline(max_current_limits[solenoid] / 1e3, color=\"tab:red\", linestyle=\"--\", linewidth=1, label=\"PCS limits\")\n", "axes[0, 0].axhline(min_current_limits[solenoid] / 1e3, color=\"tab:red\", linestyle=\"--\", linewidth=1)\n", "axes[0, 0].set_ylabel(\"Solenoid current [kA]\")\n", "axes[0, 0].legend()\n", "\n", "axes[1, 0].step(t_voltage_ms, voltages[solenoid], where=\"post\", color=colours[\"solenoid\"])\n", "axes[1, 0].set_ylabel(\"Solenoid voltage [V]\")\n", "\n", "for index in shape_coil_indices:\n", " name = active_coils[index]\n", " axes[0, 1].plot(t_ms, dynamic_currents[index] - dynamic_currents[index, 0], color=colours[name], label=name)\n", " axes[1, 1].step(t_voltage_ms, voltages[index], where=\"post\", color=colours[name], label=name)\n", "axes[0, 1].set_ylabel(\"Shape-coil current change [A]\")\n", "axes[1, 1].set_ylabel(\"Shape-coil voltages [V]\")\n", "axes[0, 1].legend(ncol=2)\n", "\n", "for axis in axes.ravel():\n", " axis.grid(alpha=0.5)\n", "for axis in axes[1]:\n", " axis.set_xlabel(\"Time [ms]\")\n", "fig.suptitle(\"Active coil currents and voltages\")\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "36", "metadata": {}, "outputs": [], "source": [ "from matplotlib.lines import Line2D\n", "\n", "# evolution of the equilibrium: four snapshots, evenly spaced in time\n", "fig, axes = plt.subplots(1, 4, figsize=(15, 4.5), dpi=80, sharex=True, sharey=True, constrained_layout=True)\n", "initial = snapshots[0]\n", "for axis, index in zip(axes, snapshot_indices):\n", " snapshot = snapshots[index]\n", " snapshot.tokamak.plot(axis=axis, show=False) # plots the active coils and passive structures\n", " snapshot.plot(axis=axis, show=False) # plots the equilibrium and its separatrix\n", " axis.set_title(f\"t = {1e3 * times[index]:.0f} ms\")\n", " axis.grid(alpha=0.5)\n", "for axis in axes[1:]:\n", " axis.set_ylabel(\"\")\n", "axes[0].set_xlim(eq.Rmin, eq.Rmax) # show the full computational domain, including the coils\n", "axes[0].set_ylim(eq.Zmin, eq.Zmax)\n", "axes[-1].legend(\n", " handles=[\n", " Line2D([], [], color=\"r\", label=\"separatrix\"),\n", " Line2D([], [], color=\"r\", marker=\"x\", linestyle=\"\", label=\"X-points\"),\n", " Line2D([], [], color=\"g\", marker=\"2\", linestyle=\"\", label=\"O-point\"),\n", " ],\n", " loc=\"lower right\",\n", " fontsize=\"small\",\n", ")\n", "\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "37", "metadata": {}, "outputs": [], "source": [ "# passive structure currents (the passive elements follow the active coils in the stored current vector)\n", "passive_currents = dynamic_currents[n_active:]\n", "passive_names = symmetric_machine.passive_names\n", "passive_centres = np.array([[np.mean(element[\"R\"]), np.mean(element[\"Z\"])] for element in symmetric_machine.passive_coils_data])\n", "scale, unit = (1e-3, \"kA\") if np.max(np.abs(passive_currents)) > 1e3 else (1.0, \"A\")\n", "\n", "fig, (time_axis, space_axis) = plt.subplots(1, 2, figsize=(13, 5), dpi=80, constrained_layout=True)\n", "\n", "# time evolution: reflected partners carry identical currents, so only the upper elements are drawn\n", "upper = [index for index, name in enumerate(passive_names) if name.endswith(\"_upper\")]\n", "for colour, index in zip(plt.cm.viridis(np.linspace(0, 1, len(upper))), upper):\n", " time_axis.plot(t_ms, scale * passive_currents[index], color=colour, label=passive_names[index].replace(\"_upper\", \"\"))\n", "time_axis.set_xlabel(\"Time [ms]\")\n", "time_axis.set_ylabel(f\"Passive structure current [{unit}]\")\n", "time_axis.set_title(\"Passive currents (upper elements; the lower partners are identical)\")\n", "time_axis.legend(ncol=2, fontsize=\"small\")\n", "time_axis.grid(alpha=0.5)\n", "\n", "# spatial distribution at the end of the simulation\n", "limit = scale * np.max(np.abs(passive_currents[:, -1]))\n", "points = space_axis.scatter(\n", " passive_centres[:, 0],\n", " passive_centres[:, 1],\n", " c=scale * passive_currents[:, -1],\n", " cmap=\"coolwarm\",\n", " vmin=-limit,\n", " vmax=limit,\n", " s=120,\n", " edgecolor=\"k\",\n", " zorder=3,\n", ")\n", "space_axis.plot(tokamak.limiter.R, tokamak.limiter.Z, \"k-\", linewidth=1.2)\n", "space_axis.set_aspect(\"equal\")\n", "space_axis.set_xlabel(\"Major radius [m]\")\n", "space_axis.set_ylabel(\"Height [m]\")\n", "space_axis.set_title(f\"Passive currents at t = {t_ms[-1]:.0f} ms\")\n", "space_axis.grid(alpha=0.5)\n", "fig.colorbar(points, ax=space_axis, label=f\"Passive structure current [{unit}]\")\n", "plt.show()\n", "\n", "upper_lower_difference = max(\n", " np.max(np.abs(passive_currents[index] - passive_currents[passive_names.index(passive_names[index].replace(\"_upper\", \"_lower\"))]))\n", " for index in upper\n", ")\n", "print(f\"Maximum upper/lower passive current difference: {upper_lower_difference:.2e} A\")\n" ] }, { "cell_type": "markdown", "id": "38", "metadata": {}, "source": [ "The passive structure currents are even in $Z$: each upper element carries exactly the same current as its lower partner. The largest changes occur when the $R_x$ ramp starts and ends. \n" ] }, { "cell_type": "markdown", "id": "39", "metadata": {}, "source": [ "Finally, we look at the wall-clock time taken by each step of the evolutive solver (this excludes the virtual PCS calculation). The red markers show the steps in which the solver re-linearised, i.e. where the relative change in the toroidal current density since the last linearisation reached the threshold (5%). Re-linearisations are the most expensive steps, as the Jacobians are rebuilt.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "40", "metadata": {}, "outputs": [], "source": [ "# wall-clock time of each evolutive solver step (the virtual PCS calculation is not included)\n", "median_step = np.median(step_times)\n", "t_step_ms = 1e3 * times[1:] # time at the end of each step\n", "relin_steps = np.flatnonzero(relinearise_criterion >= relinearise_threshold) # steps in which the solver re-linearised\n", "\n", "fig, (step_axis, total_axis) = plt.subplots(1, 2, figsize=(13, 4.5), dpi=80, constrained_layout=True)\n", "\n", "step_axis.semilogy(t_step_ms, step_times, color=\"k\", linewidth=0.8, label=\"all steps\")\n", "step_axis.semilogy(t_step_ms[relin_steps], step_times[relin_steps], \"v\", color=\"tab:red\", markersize=7, label=f\"re-linearisations ({len(relin_steps)})\")\n", "step_axis.axhline(median_step, color=\"tab:blue\", linestyle=\"--\", linewidth=1, label=f\"median step ({1e3 * median_step:.0f} ms)\")\n", "step_axis.set_xlabel(\"Time [ms]\")\n", "step_axis.set_ylabel(\"Wall-clock time per solver step [s]\")\n", "step_axis.set_title(\"Time per step\")\n", "step_axis.legend(loc=\"lower right\")\n", "step_axis.grid(alpha=0.5, which=\"both\")\n", "\n", "total_axis.plot(t_step_ms, np.cumsum(step_times), color=\"k\")\n", "for step in relin_steps:\n", " total_axis.axvline(t_step_ms[step], color=\"tab:red\", linestyle=\":\", linewidth=1)\n", "total_axis.plot([], [], color=\"tab:red\", linestyle=\":\", label=\"re-linearisation\")\n", "total_axis.set_xlabel(\"Simulated time [ms]\")\n", "total_axis.set_ylabel(\"Cumulative wall-clock time [s]\")\n", "total_axis.set_title(f\"Total: {np.sum(step_times):.0f} s for {t_step_ms[-1]:.0f} ms of plasma evolution\")\n", "total_axis.legend()\n", "total_axis.grid(alpha=0.5)\n", "plt.show()\n", "\n", "print(f\"{len(step_times)} steps of {1e3 * dt:.1f} ms | median {1e3 * median_step:.0f} ms | total {np.sum(step_times):.0f} s\")\n", "print(f\"{len(relin_steps)} re-linearisations, at t = {np.round(1e3 * times[relin_steps], 1)} ms\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "41", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "42", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "43", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "freegsnke", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }